package com.hacker.spider.wallhaven;

import java.util.List;

import com.hacker.spider.IHandler;
import com.hacker.spider.ISpiderTask;
import com.hacker.spider.concurrent.ResultActuator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class WallHavenTask implements ISpiderTask {

  private final String missionAddress;

  private final IHandler<List<WallHavenImage>> handler;

  public WallHavenTask(String missionAddress, IHandler<List<WallHavenImage>> handler) {
    this.missionAddress = missionAddress;
    this.handler = handler;
  }

  @Override public void run() {
    try {
      Thread.sleep(1000);
      getLogger().info("begin Crawling path:{}, handler:{}", missionAddress, handler.getClass().getName());
      Document document = Jsoup.connect(missionAddress).get();
      handler.handle(document);
    } catch (Throwable e) {
      getLogger().error("{} crawling {} fail, retry.", Thread.currentThread().getName(), missionAddress, e);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException interruptedException) {
        interruptedException.printStackTrace();
      }
      ResultActuator.getInstance().rejectRetry(this);
    }
  }
}
